package com.project.utils;

import com.alibaba.fastjson.JSON;
import com.project.bean.OrderBean;
import com.project.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;

@Service
@ServerEndpoint("/socketService")
public class WebSocketUtil {

    private static OrderService orderService;

    @Autowired
    private void setOrderService(OrderService orderService) {
        WebSocketUtil.orderService = orderService;
    }

    @OnOpen
    public void open(Session session) throws IOException {
        session.getBasicRemote().sendText("与后台已经建立连接，，，，");
    }

    @OnMessage
    public void getMessage(String message, Session session) throws IOException, InterruptedException {
        System.out.println("前端发送回来的消息" + message);
        String[] messages = message.split("_");
        while (true) {
            //每各2s往前端发送数据
            List<OrderBean> list = orderService.findAllOrder(messages[0], messages[1]);
            session.getBasicRemote().sendText(JSON.toJSONString(list));
            Thread.sleep(2000);
        }
    }
}
